package com.cloud.manager.web.controller;

import com.cloud.manager.core.config.CloudConfig;
import com.cloud.manager.core.result.Result;
import com.cloud.manager.core.result.ResultCreator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.io.File;
import java.io.IOException;

/**
 * 描述：
 *
 * @author FineEx   2021/11/18
 * @version 1.0
 */
@EnableSwagger2
@Api(tags = "文件管理")
@RestController
@RequestMapping("/file")
public class FileController {


    @ApiOperation(value = "文件上传")
    @ApiImplicitParam(name = "file", value = "文件上传", required = true, dataType = "MultipartFile", allowMultiple = true, paramType = "query")
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return ResultCreator.fail("上传失败，文件内容为空！");
        }
        String fileName = file.getOriginalFilename();
        File localFile = new File(CloudConfig.getUploadPath() + File.separator + fileName);
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(localFile);
        } catch (IOException e) {
            return ResultCreator.fail("文件上传失败，绝对路径：{}" + localFile.getPath());
        }
        return ResultCreator.success("上传成功");
    }
}
